package com.tong.embeddedvr.service.impl;

import com.tong.embeddedvr.config.VerCodeMsgConfig;
import com.tong.embeddedvr.Mapper.UserMapper;
import com.tong.embeddedvr.constant.ConstantPool;
import com.tong.embeddedvr.dto.UserInputDTO;
import com.tong.embeddedvr.dto.UserOutputDTO;
import com.tong.embeddedvr.entity.UserEntity;
import com.tong.embeddedvr.service.UserService;
import com.tong.embeddedvr.utils.CommonUtil;
import com.tong.embeddedvr.utils.MsgSendUtil;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {

    /**
     * 注:
     * 1. 返回值Jackson的异常在Controller层处理
     * 2. 中间过程的异常在Service层处理
     */

    @Autowired
    private UserMapper userMapper;

    /*依赖的注入可以近似为一个递归的过程,如果某个类不是在spring容器中(也就是没有@component注解),那么它的属性的@Autowird也就无法完成*/
    @Autowired
    private VerCodeMsgConfig verCodeMsgConfig;

    private final Logger logger = LoggerFactory.getLogger(UserService.class);

    @Override
    public String sendRegisterMsg(HttpSession session, UserInputDTO userInputDTO) {
        String res;
        DefaultMapperFactory mapperFactory = CommonUtil.getMapperFactory();
        UserEntity prop = mapperFactory.getMapperFacade().map(userInputDTO, UserEntity.class);
        //检查手机号是否有效
        UserOutputDTO[] user = userMapper.getUserByTelephone(prop);
        if(user.length==0){  //user作为一个数组必不为空,所以应该判断user.length
            String userTelephone = userInputDTO.getUserTelephone();
            Random random = new Random();
            Integer code = random.nextInt(100000) + 100000;
            try{
                MsgSendUtil.sendVerMsg(verCodeMsgConfig,userTelephone,code.toString());
                session.setAttribute(ConstantPool.TELEPHONE,userTelephone);
                session.setAttribute(ConstantPool.CODE,code.toString());
                logger.info("短信接收手机号:[{}] 验证码:[{}]",userTelephone,code);
                res = CommonUtil.ajaxReturn("信息发送成功,请查收!");
                //实际上这里的错误检测需要查看对应的返回值
            }catch (Exception e){
                e.printStackTrace();
                logger.error("信息发送错误:telephone:[{}]|code:[{}]",userTelephone,code);
                res = CommonUtil.ajaxReturn(400,"发送失败或无效,请检查手机号后重试!");
            }
        }else{
            logger.info("手机号已注册:[{}]",userInputDTO.getUserTelephone());
            res = CommonUtil.ajaxReturn(300,"该手机号已注册,请勿重复绑定!");  //资源限制,使用300错误
        }
        return res;
    }

    @Override
    public String sendLoginMsg(HttpSession session, UserInputDTO userInputDTO) {
        String res;
        DefaultMapperFactory mapperFactory = CommonUtil.getMapperFactory();
        UserEntity prop = mapperFactory.getMapperFacade().map(userInputDTO, UserEntity.class);
        //检查手机号是否有效
        UserOutputDTO[] users = userMapper.getUserByTelephone(prop);
        if(users!=null){
            String userTelephone = userInputDTO.getUserTelephone();
            Random random = new Random();
            Integer code = random.nextInt(100000) + 100000;
            try{
                MsgSendUtil.sendVerMsg(verCodeMsgConfig,userTelephone,code.toString());
                session.setAttribute(ConstantPool.TELEPHONE,userTelephone);
                session.setAttribute(ConstantPool.CODE,code.toString());
                logger.info("短信接收手机号:[{}] 验证码:[{}]",userTelephone,code);
                res = CommonUtil.ajaxReturn("信息发送成功,请查收!");
                //实际上这里的错误检测需要查看对应的返回值
            }catch (Exception e){
                e.printStackTrace();
                logger.error("信息发送错误:telephone:[{}]|code:[{}]",userTelephone,code);
                res = CommonUtil.ajaxReturn(400,"发送失败或无效,请检查手机号后重试!");
            }
        }else{
            logger.info("该手机绑定的账号不存在:[{}]",userInputDTO.getUserTelephone());
            res = CommonUtil.ajaxReturn(400,"信息发送失败,请检查手机号是否正确!");
        }
        return res;
    }


    @Override
    public String register(UserInputDTO userInputDTO, HttpSession session){
        String res;
        DefaultMapperFactory mapperFactory = CommonUtil.getMapperFactory();
        UserEntity prop = mapperFactory.getMapperFacade().map(userInputDTO, UserEntity.class);
        try{
            String telephone = (String)session.getAttribute(ConstantPool.TELEPHONE);
            String code = (String)session.getAttribute(ConstantPool.CODE);
            if(!(userInputDTO.getUserTelephone().equals(telephone)&&userInputDTO.getCode().equals(code))){
                logger.info("注册失败:手机号或者验证码错误|用户信息:[{}]",userInputDTO);
                return CommonUtil.ajaxReturn(400,"手机号或者验证码错误,请重试!");
            }
        }catch (Exception e){
            logger.error("注册失败:手机号或者验证码错误|用户信息:[{}]",userInputDTO);
            e.printStackTrace();
            return CommonUtil.ajaxReturn(400,"手机号或者验证码错误,请重试!");
        }
        session.removeAttribute(ConstantPool.TELEPHONE);
        session.removeAttribute(ConstantPool.CODE);
        UserOutputDTO[] userOutputDTOS = userMapper.usernameCount(prop);
        if(userOutputDTOS.length!=0){
            try{
                userMapper.addUser(prop);
                UserOutputDTO user = userMapper.getUserByUsernameAndPassword(prop);
                session.setAttribute(ConstantPool.USER,user);
                logger.info("用户注册成功:[{}]",prop);
                res = CommonUtil.ajaxReturn("注册成功");
            }catch (Exception e){
                e.printStackTrace();
                res = CommonUtil.ajaxReturn(400,"注册失败,请检查数据的有效性!");
            }
        }else{
            res = CommonUtil.ajaxReturn(400,"用户已注册");
        }
        return res;
    }

    @Override
    public String login(HttpSession session, UserInputDTO userInputDTO){
        String res;
        DefaultMapperFactory mapperFactory = CommonUtil.getMapperFactory();
        UserEntity prop = mapperFactory.getMapperFacade().map(userInputDTO, UserEntity.class);
        try{
            Integer loginType = userInputDTO.getLoginType();
            if(loginType==0){
                UserOutputDTO user = userMapper.getUserByUsernameAndPassword(prop);
                if(user != null){
                    session.setAttribute(ConstantPool.USER,user);
                    res = CommonUtil.ajaxReturn(user);
                }else{
                    res = CommonUtil.ajaxReturn(400,"登陆失败,请检查用户名和密码是否正确!");
                }
            }else if(loginType==1){
                String userTelephone = (String)session.getAttribute(ConstantPool.TELEPHONE);
                String code = (String)session.getAttribute(ConstantPool.CODE);
                if(userTelephone!=null&&code!=null&&userTelephone.equals(userInputDTO.getUserTelephone())&&code.equals(userInputDTO.getCode())){
                    System.out.println();
                    UserOutputDTO[] users = userMapper.getUserByTelephone(prop);
                    if(users!=null){
                        //登陆成功,先清理session中的无效数据,同时在session中增加user
                        session.removeAttribute(ConstantPool.TELEPHONE);
                        session.removeAttribute(ConstantPool.CODE);
                        session.setAttribute(ConstantPool.USER,users[0]);
                        res = CommonUtil.ajaxReturn(users[0]);
                    }else{
                        res = CommonUtil.ajaxReturn(400,"登陆失败,该手机号未注册");
                    }
                }else{
                    res = CommonUtil.ajaxReturn(400,"登陆失败,请输入手机号或验证码");
                }
            }else{
                res = CommonUtil.ajaxReturn(400,"登陆失败,请选择正确的登陆类型");
            }
        }catch (Exception exception){
            exception.printStackTrace();
            logger.error("登陆失败:[{}]",prop);
            res = CommonUtil.ajaxReturn(400,"登陆失败!");
        }
        return res;
    }

    @Override
    public String updateInformation(UserInputDTO userInputDTO){
        String res;
        DefaultMapperFactory mapperFactory = CommonUtil.getMapperFactory();
        UserEntity prop = mapperFactory.getMapperFacade().map(userInputDTO, UserEntity.class);
        try{
            userMapper.updateInformation(prop);
            res = CommonUtil.ajaxReturn("更新成功!");
        }catch(Exception e){
            e.printStackTrace();
            logger.error("用户信息更新失败:[{}]",prop);
            res = CommonUtil.ajaxReturn(400,"更新失败,请确保护数据符合要求");
        }
        return res;
    }
}
